var
	sProject = 'tmp',
	sAjaxMethod = 'POST',
	sAjaxError = 'При загрузке данных произошла ошибка.',
	sAjaxUpdateError = 'При отправке данных произошла ошибка.',
	sAjaxUpdateSucces = 'Данные успешно сохранены.'
;

function clearSelect(oSelect){
	oSelect.html('<option value="">&nbsp;</option>').val('');
}

function fillSelect(oSelect, oData){
	for(var sKey in oData){
		oSelect.append(
			'<option value="'
			+ sKey +
			'">'
			+ oData[sKey] +
			'</option>'
		);
	}
	var sValue = oSelect.data('value') || '';
	oSelect.val(sValue);
	var oForm = ZForms.getFormById(oSelect.closest('form.zf').attr('id'));
	var oWidget = oForm.getWidgetById(oSelect.attr('id'));
	oWidget.setValue(oWidget.createValue('sValue'));
}

function loadItems(aFields, oData, sPath, fCallback){
	for(var i = 0, n = aFields.length; i < n; i++){
		aFields[i].parent().addClass('waiting');
	}

	oData['pmp_project'] = sProject;

	var oForm = aFields[0].closest('form.zf');
	lockForm(oForm);

	$.ajax({
		type: sAjaxMethod,
		url: sPath,
		data: oData,
		dataType: 'json',
		cache : false,

		success : function(oData){
			unlockForm(oForm);
			for(var i = 0, n = aFields.length; i < n; i++){
				aFields[i].parent().removeClass('waiting');
			}
			if(fCallback){
				fCallback(oData);
			}
			if(window.initSessionTimer) initSessionTimer();
		},

		error : function(){
			unlockForm(oForm);
			for(var i = 0, n = aFields.length; i < n; i++){
				aFields[i].parent().removeClass('waiting');
			}
		}
	});
}

function initForm(oForm){
	oForm.find('input:submit').click(function(){
		if(checkForm(oForm)){
			$(this).removeClass('hover');
			oForm[0].submit();
		}
	});
}

function initAjaxForm(oForm, sPath, fSuccessCallback, fErrorCallback){
	ZForms.buildForm(oForm[0]);

	oForm.find('input:submit').click(function(){
		if(checkForm(oForm)){
			$(this).removeClass('hover');

			submitAjaxForm(
				oForm,
				sPath,
				fSuccessCallback,
				fErrorCallback
			);
		}
	});
}

function initFcukForm(oForm, sPath, fSuccessCallback, fErrorCallback){

	oForm.find('input:submit').click(function(){
		if(checkForm(oForm)){
			$(this).removeClass('hover');
			submitAjaxForm(
				oForm,
				sPath,
				fSuccessCallback,
				fErrorCallback
			);
		}
	});
}

function submitAjaxForm(oForm, sPath, fSuccessCallback, fErrorCallback){
	if(oForm.find('input:file').length){

		submitFormWithFiles(oForm, sPath, fSuccessCallback, fErrorCallback);

	} else {

		var oData = oForm.serializeArray();

		lockForm(oForm);

		$.ajax({
			type: sAjaxMethod,
			url: sPath,
			data: oData,
			dataType: 'json',
			cache : false,

			success : function(oData){
				console.log(oData);
				if(oData.result.redirect){
					document.location.href = oData.result.redirectUrl;
				} else {
					unlockForm(oForm);

					if(oData.result.success){
						oForm.removeClass('zf-submitted');

						if(fSuccessCallback){
							fSuccessCallback(oForm, oData);
						}

						showOKMessage(
							oForm,
							((oData.result.successText) ? oData.result.successText : sAjaxUpdateSucces)
						);

					} else {
						if(fErrorCallback){
							fErrorCallback(oForm);
						}

						showErrorMessage(
							oForm,
							((oData.result.errorText) ? oData.result.errorText : sAjaxUpdateError)
						);
					}

					if(window.initSessionTimer) initSessionTimer();
				}
			},

			error : function(){
				unlockForm(oForm);
console.log("error");
				if(fErrorCallback){
					fErrorCallback(oForm);
				}

				showErrorMessage(
					oForm,
					sAjaxUpdateError
				);

				return false;
			}

		});

		return false;
	}
	return false;
}


function submitFormWithFiles(oForm, sPath, fSuccessCallback, fErrorCallback){
	var t = new Date().getTime();
	var sFrameID = 'upload_frame_' + t;
	var oFrame = $('<iframe id="' + sFrameID + '" name="' + sFrameID + '" src="javascript:;" style="display:none">').appendTo(document.body);

	oForm.attr('target', sFrameID);
	oForm.attr('action', sPath);

	$(oFrame).load(function(){

		var oData = oFrame.contents().find('*:last').html();
		try{ oData = eval('(' + oData + ')'); } catch(e) { oData = false; }

		if(oData){
			if(oData.result.redirect){
				document.location.href = oData.result.redirectUrl;
			} else {
				unlockForm(oForm);

				if(oData.result.success){
					oForm.removeClass('zf-submitted');

					if(fSuccessCallback){
						fSuccessCallback(oForm, oData);
					}

					showOKMessage(
						oForm,
						((oData.result.successText) ? oData.result.successText : sAjaxUpdateSucces)
					);
				} else {
					if(fErrorCallback){
						fErrorCallback(oForm, oData);
					}

					showErrorMessage(
						oForm,
						((oData.result.errorText) ? oData.result.errorText : sAjaxUpdateError)
					);
				}
			}
		} else {
			unlockForm(oForm);

			if(fErrorCallback){
				fErrorCallback(oForm);
			}

			showErrorMessage(
				oForm,
				sAjaxUpdateError
			);
		}

	});

	oForm[0].submit();

	lockForm(oForm);
}


function checkForm(oForm){
	bResult = (oForm.find('tr.zf-required,dl.zf-required,dl.zf-invalid,fieldset.zf-required,fieldset.zf-invalid').length == 0);
	return bResult;
}

function unlockForm(oForm){
	oForm.removeClass('zf-disabled');
	oForm.find('dl,input,.zf').each(function(){
		$(this).removeClass('zf-disabled');
		$(this)[0].disabled = false;
	});
	oForm.find('.zf-always-disabled')
		.removeClass('zf-always-disabled')
		.addClass('zf-disabled')
		.find('input,select').attr('disabled', true)
	;
	oForm.find('.buttons').removeClass('waiting');
}

function lockForm(oForm){
	oForm.addClass('zf-disabled');
	oForm.find('.zf-disabled').addClass('zf-always-disabled');
	oForm.find('dl,input,.zf').each(function(){
		$(this).addClass('zf-disabled');
		$(this)[0].disabled = true;
	});
	oForm.find('.buttons').addClass('waiting');
}

function showOKMessage(oForm, sText){ 
	hideMessage(oForm.find('.zf-result .zf-error')); 
	showMessage(oForm.find('.zf-result .zf-ok'), sText);
}

function showErrorMessage(oForm, sText){
	hideMessage(oForm.find('.zf-result .zf-ok'));
	showMessage(oForm.find('.zf-result .zf-error'), sText);
}

function showMessage(oLabel, sText){
	hideMessage(oLabel);
	oLabel.html(sText);
//	roundMessage(oLabel);
	oLabel.css('display', 'block');
	oLabel.oneTime(6000, function(){
		oLabel.fadeOut(500, function(){ $(this).css('display', 'none'); });
	});
}

function hideMessage(oLabel){
	oLabel.stopTime();
	oLabel.stop();
	oLabel.css('display', 'none');
	oLabel.html('');
}

function roundMessage(oLabel){
	//oLabel.prepend('<div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div>');
}

function phoneCheck(oWidget) {
	var aChildren = oWidget.oParent.getChildren();
	oVal1 = aChildren[0].getValue(),
	oVal2 = aChildren[1].getValue();
	return (oVal2.isEmpty() && oVal1.isEmpty()) || (oVal1.match(/^\d{3}$/) && oVal2.match(/^\d{7}$/));
}

function birthdayCheck(oWidget) {
	var bResult = true;

	var aWidgets = oWidget.getChildren();

	var aDate = [
		parseInt(aWidgets[0].getValue().get()),
		parseInt(aWidgets[1].getValue().get()),
		parseInt(aWidgets[2].getValue().get())
	];

	if(aDate[0] && aDate[1] && aDate[2]){

		var dtBirthDate = new Date(aDate[2], aDate[1] - 1, aDate[0]);

		var bCorrectDate = (
			(aDate[2] - dtBirthDate.getFullYear()) == 0 &&
			(aDate[1] - dtBirthDate.getMonth()) == 1 &&
			(aDate[0] - dtBirthDate.getDate()) == 0
		)

		var bMore18 = (dtBirthDate < dtMax);

		if(bMore18){
			oWidget.removeClass('zf-invalid-less18');
		} else {
			oWidget.addClass('zf-invalid-less18');
		}

		bResult = (bCorrectDate && bMore18);
	}

	return bResult;
}